package org.example.SolutionNew002;

public class LinkedList07 {
    public static void main(String[] args) {
        LinkedList07 l = new LinkedList07();
        ListNode head1 = new ListNode(9);
        head1.next = new ListNode(9);
        head1.next.next = new ListNode(9);
        ListNode head2 = new ListNode(9);
//        head2.next = new ListNode(6);
//        head2.next.next = new ListNode(4);
        ListNode res=l.addTwoNumbers(head1, head2);
        while(res!=null){
            System.out.println(res.val);
            res=res.next;
        }
    }

    public ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        int carry= 0;
        ListNode head=new ListNode(-1);
        ListNode temp=head;
        while(l1!=null&&l2!=null){
            int val=l1.val+l2.val+carry;
            if(val>=10){
                carry=1;
                val-=10;
            }else{
                carry=0;
            }
            temp.next=new ListNode(val);
            l1=l1.next;
            l2=l2.next;
            temp=temp.next;
        }
        ListNode temp1=null;
        if(l1==null){
            temp1=l2;
        }else{
            temp1=l1;
        }
        while(temp1!=null){
            int val=temp1.val+carry;
            if(val>=10){
                carry=1;
                val-=10;
            }else{
                carry=0;
            }
            temp.next=new ListNode(val);
            temp1=temp1.next;
            temp=temp.next;
        }
        if(carry!=0){
            temp.next=new ListNode(carry);
        }
        return head.next;
    }

    //写的不是很好重新写一下
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head=null,curr=head;
        int carry=0;
        while(l1!=null||l2!=null){
            int num1=l1!=null?l1.val:0;
            int num2=l2!=null?l2.val:0;
            int val=num1+num2+carry;
            carry=val/10;
            if(head==null){
                head=curr=new ListNode(val%10);
            }else{
                curr.next=new ListNode(val%10);
                curr=curr.next;
            }
            if(l1!=null){
                l1=l1.next;
            }
            if(l2!=null){
                l2=l2.next;
            }
        }
        if(carry!=0){
            curr.next=new ListNode(carry);
        }
        return head;
    }
}
